import { Label } from "@renderer/components/ui/base/field";
import { Select } from "@renderer/components/ui/select";
import langs from "@renderer/i18n/langs";
import { useLanguageSetting } from "@renderer/queries";
import type { Language } from "@shared/triplit/types";
import type { Key } from "react-aria-components";
import { useTranslation } from "react-i18next";

const { configService } = window.service;

export function LanguageSelector() {
  const { t, i18n } = useTranslation();

  const { data: lang } = useLanguageSetting();
  const currentLang = langs.find((l) => l.key === (lang ?? "zh")) ?? langs[0];

  const handleLanguageChange = async (key: Key | null) => {
    const newLang = key?.toString() ?? "";
    await Promise.all([
      configService.setAppLanguage(newLang as Language),
      i18n.changeLanguage(newLang),
    ]);
  };

  return (
    <Select
      label={
        <Label className="text-label-fg">
          {t("settings.general-settings.language.label")}
        </Label>
      }
      items={langs.map((lang) => ({
        key: lang.key,
        text: lang.nativeName,
        prefix: lang.prefix,
      }))}
      selectedKey={currentLang.key}
      onSelectionChange={handleLanguageChange}
    />
  );
}
